/*
 * Copyright 2008-2009 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ssn.task.web;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import ssn.common.view.AjaxView;
import ssn.common.web.CommonController;
import ssn.task.service.TaskService;
import ssn.task.vo.TaskVO;
import egovframework.rte.fdl.cmmn.exception.EgovBizException;
import egovframework.rte.fdl.string.EgovStringUtil;


/**  
 * @Class Name : 
 * @Description : 
 * @Modification Information  
 * @
 * @  수정일      수정자              수정내용
 * @ ---------   ---------   -------------------------------
 * @ 2013.10.09           최초생성
 * 
 * @since 2013. 09.30
 * @version 1.0
 * @see
 */
@SuppressWarnings("rawtypes")
@Controller
public class TaskController extends CommonController{
	
    @Resource(name = "taskService")
    private TaskService taskService;

    /**
	 * 글 목록을 조회한다. 
	 * @param 
	 * @param model
	 * @return 
	 * @exception Exception
	 */
    @RequestMapping(value="/task/taskList.do")
    public String taskList(@ModelAttribute("taskVO") TaskVO taskVO,
    			ModelMap model) throws Exception {
    	
    	/** pageUnit : 페이지 리스트 개수, pageSize : 페이징 개수
    	taskVO.setPageUnit(15);
    	taskVO.setPageSize(15);
    	*/
    	Map resultMap = null;
    	List resultList = null;
        if(loginSessionInfo.get().isAdmin()){
        	resultMap = taskService.selectTaskListAdmin(taskVO);
        	resultList = (List)resultMap.get("resultList");
        }else{
        	taskVO.setSto_area_key(loginSessionInfo.get().getSsa_area_key());
        	resultMap = taskService.selectTaskList(taskVO);
        	resultList = (List)resultMap.get("resultList");
        }
    	taskVO.setTotalRecordCount((Integer)resultMap.get("resultListCnt"));
    	model.addAttribute("resultList", resultList);
    	model.addAttribute("taskVO", taskVO);
        
        return "/task/taskList";
    }
    
    /**
     * 뷰페이지
     * @param taskVO
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/task/taskView.do")
    public String taskView(@ModelAttribute("taskVO") TaskVO taskVO,
    			ModelMap model) throws Exception {
    	
    	if(EgovStringUtil.isEmpty(taskVO.getSto_task_key())){
    		throw new EgovBizException(propertiesService.getString("info.nodata.msg"));
    	}
    	model.addAttribute("resultVO", getTaskInfo(taskVO, loginSessionInfo.get().isAdmin()));
        return "/task/taskView";
    }
    
    /**
     * 업무연락 정보를 가져온다.
     * @param taskVO
     * @param adminFlag
     * @return
     * @throws Exception
     */
    private TaskVO getTaskInfo(TaskVO taskVO, boolean adminFlag) throws Exception{
    	TaskVO resultVO = null;
    	if(adminFlag){
    		resultVO = taskService.selectTaskInfoAdmin(taskVO);
    	}else{
    		resultVO = taskService.selectTaskInfo(taskVO, loginSessionInfo.get().getSsa_area_key());
    	}
    	if(resultVO != null){
    		resultVO.setSearchParam(taskVO);
    	}
    	return resultVO;
    }
    
    /**
     * 글쓰기 수정폼
     * @param taskVO
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/task/taskWriteForm.do")
    public String taskWriteForm(@ModelAttribute("taskVO") TaskVO taskVO,
    			ModelMap model) throws Exception {
    	
    	if(!loginSessionInfo.get().isAdmin()){
    		throw new EgovBizException(propertiesService.getString("info.grade.msg"));
    	}
    	
    	if(EgovStringUtil.isNotEmpty(taskVO.getSto_task_key())){
    		model.addAttribute("resultVO", getTaskInfo(taskVO, loginSessionInfo.get().isAdmin()));
    	}else{
    		model.addAttribute("resultVO", taskVO);
    		Map resultOtherInfo = taskService.selectTaskOtherInfo();
    		model.addAttribute("serviceareaList", resultOtherInfo.get("serviceareaList"));	// 휴게소 목록
    	}
        return "/task/taskWriteForm";
    }
    
    @RequestMapping(value="/task/taskSave.do", method=RequestMethod.GET)
    public String taskWriteFormGet(ModelMap model) throws Exception {
    	return "redirect:/task/taskWriteForm.do";
    }
    
    /**
     * 저장/수정
     * @param taskVO
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/task/taskSave.do", method=RequestMethod.POST)
    public ModelAndView taskSave(@ModelAttribute("taskVO") @Valid TaskVO taskVO, BindingResult bindingResult) throws Exception {
    	ModelAndView mav = new ModelAndView();
    	mav.setView(new RedirectView(servletContext.getContextPath()+"/task/taskView.do"));
    	if(bindingResult.hasErrors()){
    		for(FieldError error :  bindingResult.getFieldErrors()){
    			mav.addObject("error_"+error.getField(), error.getDefaultMessage());
    		}
    		Map resultOtherInfo = taskService.selectTaskOtherInfo();
    		mav.setViewName("/task/taskWriteForm");
    		mav.addObject("serviceareaList", resultOtherInfo.get("serviceareaList"));
    		mav.addObject("resultVO", taskVO);
			return mav;
    	}
    	if(EgovStringUtil.isNotEmpty(taskVO.getSto_task_key())){
    		taskVO.setSto_modi_id(loginSessionInfo.get().getSsa_login_id());
    		taskService.updateTaskInfo(taskVO);
    	}else{
    		taskVO.setSto_regi_id(loginSessionInfo.get().getSsa_login_id());
    		taskService.insertTaskInfo(taskVO);
    	}
    	mav.addObject("sto_task_key", taskVO.getSto_task_key());
    	mav.addObject("pageIndex", taskVO.getPageIndex());
    	return mav;
    } 
    
    /**
     * 삭제
     * @param taskVO
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/task/taskUpdate.do", method=RequestMethod.POST)
    public ModelAndView taskUpdate(@ModelAttribute("taskVO") TaskVO taskVO) throws Exception {
    	ModelAndView mav = new ModelAndView();
    	mav.setView(new RedirectView(servletContext.getContextPath()+"/task/taskView.do"));
    	if(EgovStringUtil.isNotEmpty(taskVO.getSto_task_key())){
    		taskVO.setSto_modi_id(loginSessionInfo.get().getSsa_login_id());
    		taskService.updateStatusTaskInfo(taskVO);
    	}else{
    		throw new EgovBizException(propertiesService.getString("info.nodata.msg"));
    	}
    	mav.addObject("sto_task_key", taskVO.getSto_task_key());
    	mav.addObject("pageIndex", taskVO.getPageIndex());
    	return mav;
    } 
    
    /**
     * 파일 삭제
     * @param userVO
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/task/deleteAttachFile.do", method=RequestMethod.POST)
    public ModelAndView deleteAttachFile(@RequestParam(value="sto_task_key") String sto_task_key) throws Exception {
    	ModelAndView mav = new ModelAndView(new AjaxView());
    	String result = "false";
    	if(taskService.deleteTaskAttachFile(sto_task_key))
    		result = "true";
    	mav.addObject("result", result);
    	return mav;
    } 
}
